package cn.jwcat.controller;

import cn.jwcat.entity.File;
import cn.jwcat.entity.Password;
import cn.jwcat.entity.Staff;
import cn.jwcat.service.IFileService;
import cn.jwcat.service.IStaffService;
import cn.jwcat.utils.JwtTokenUtil;
import cn.jwcat.utils.otherUtils;
import cn.jwcat.utils.result.Result;
import cn.jwcat.utils.result.ResultCodeEnum;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;

/**
 * 管理员操作
 */
@RestController
@Transactional
@RequestMapping("/staff")
public class StaffController {
    @Resource
    JwtTokenUtil jwtTokenUtil;

    @Resource
    IFileService fileService;

    @Resource
    IStaffService staffService;

    @PostMapping("/upload")
    @ApiOperation("管理员图片文件上传")
    public Result uploadPic(HttpServletRequest request, MultipartFile file) throws IOException {
        Staff staff = jwtTokenUtil.getStaffFromRequest(request);
        File uploadFile = fileService.upload(file);
        LambdaUpdateWrapper<Staff> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Staff::getPicture, uploadFile.getVirtualPath()).eq(Staff::getStaffId, staff.getStaffId());
        boolean bool = this.staffService.update(updateWrapper);
        if (!bool) return Result.error("文件上传失败，请重新操作");
        HashMap<String, String> map = new HashMap<>();
        map.put("picture", uploadFile.getVirtualPath());
        return Result.success(map);
    }

    @PutMapping
    @ApiOperation("修改基本信息操作")
    public Result update(@RequestBody Staff staff) {
        System.out.println(staff);
        Staff staffs = staffService.updateStaff(staff);
        if (staffs == null) return Result.api(ResultCodeEnum.ERROR);
        Staff delStaff = otherUtils.delStaff(staffs);
        delStaff.setBool(staffService.get(delStaff.getStaffId()));
        return Result.success(delStaff);
    }

    @PutMapping("/pwd")
    @ApiOperation("修改密码")
    public Result changePwd(@RequestBody Password password) throws Exception {
        System.out.println(password);
        return staffService.changePwd(password);
    }
}
